from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404

from . import models


def index(request, num=None):
    if num is None:
        books = models.Book.objects.all()
    else:
        num = int(num)
        books = models.Book.objects.all()[:num]
    context = {'books': books, 'total': len(books)}
    response = render(request, "app1/index.html", context=context)
    return response


def detail(request, pk):
    # book = get_object_or_404(models.Book, pk=pk)
    try:
        book = models.Book.objects.get(pk=pk)
    except models.Book.DoesNotExist:
        return HttpResponse('book not foud')
    context = {'book': book}
    return render(request, "app1/detail.html", context=context)


def about(request):
    return render(request, "app1/about.html")
